package cn.bupt.adt.controller.inf;

import cn.bupt.adt.constant.Constants;
import cn.bupt.adt.entity.autogenerate.FeeConf;
import cn.bupt.adt.entity.autogenerate.InstitutionAppUser;
import cn.bupt.adt.entity.autogenerate.InstitutionView;
import cn.bupt.adt.entity.autogenerate.Withdraw;
import cn.bupt.adt.service.IFeeConfService;
import cn.bupt.adt.service.IInstitutionAppUserService;
import cn.bupt.adt.service.IWithdrawService;
import cn.bupt.adt.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("/publicApp/institution")
public class InstitutionAppPublicController {

    @Autowired
    IInstitutionAppUserService institutionAppUserService;

    @Autowired
    IWithdrawService withdrawService;

    @Autowired
    IFeeConfService feeConfService;

    /**
     * 机构登录
     *
     * @param user
     * @param request
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public Object login(InstitutionAppUser user, HttpServletRequest request) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if ("GET".equals(request.getMethod()) || null == user) {
            return NetDataAccessUtil.error(-3).resultDesp("请求错误");
        }
        InstitutionView ins = institutionAppUserService.getInstitutionByAccount(user.getAccount());
        if (ins == null) {
            return NetDataAccessUtil.error(-1).resultDesp("该用户不存在");
        }
        if (!ins.getPasswd().equals(MD5Util.MD5(user.getPasswd()))) {
            return NetDataAccessUtil.error(-2).resultDesp("密码错误");
        }
        // 登录成功，清除之前的token信息
        Jedis redis = RedisUtil.getJedis();
        Date loginTime = new Date();
        String key = UserUtil.generateToken(user.getAccount(), df.format(loginTime));
        if (redis.exists(key)) {
            redis.del(key);
            RedisUtil.returnResource(redis);
        }
        institutionAppUserService.updateLoginTimeById(ins.getId(), loginTime);
        // 生成token,存token到redis
        String token = UserUtil.generateToken(user.getAccount(), df.format(loginTime));
        RedisUtil.set(token, ins.getId());
        // 事先拼接用户图像的完整路径
        ins.setPortrait("http://" + IPUtil.getIpAddr(request) + ":" + request.getLocalPort() + "/"
                + Constants.IMAGE_PATH + ins.getPortrait());
        return NetDataAccessUtil.success().content(UserUtil.constructInsUserResp(ins, token)).resultDesp("登录成功");
    }

    /**
     * 机构登出
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public Object logout(HttpServletRequest request) {
        Integer userId = (Integer) request.getAttribute("userId");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        InstitutionAppUser ins = institutionAppUserService.getInstitutionById(userId);
        String key = MD5Util.MD5(ins.getAccount() + df.format(ins.getLoginTime()));
        if (RedisUtil.exist(key)) {
            RedisUtil.del(key);
            return NetDataAccessUtil.success().resultDesp("登出成功");
        }
        return NetDataAccessUtil.error(0).resultDesp("登出失败");
    }

    /**
     * 机构修改密码
     *
     * @param request
     * @param passwd
     * @param newPasswd
     * @return
     */
    @RequestMapping(value = "/changePasswd", method = RequestMethod.POST)
    @ResponseBody
    public Object changePasswd(HttpServletRequest request, String passwd, String newPasswd) {
        Integer userId = (Integer) request.getAttribute("userId");
        InstitutionAppUser ins = institutionAppUserService.getInstitutionById(userId);
        if (!MD5Util.MD5(passwd).equals(ins.getPasswd())) {
            return NetDataAccessUtil.error(0).resultDesp("输入旧密码不正确，请确认您的旧密码");
        }
        if (institutionAppUserService.changePasswd(ins, newPasswd)) {
            RedisUtil.del(request.getParameter("token"));
            return NetDataAccessUtil.success().resultDesp("修改密码成功,请重新登录");
        }
        return NetDataAccessUtil.error().resultDesp("因网络或其他原因，修改密码失败，请稍后尝试");
    }

    /**
     * 机构提现
     *
     * @param request
     * @param withdraw
     * @return
     */
    @RequestMapping(value = "/withdraw", method = RequestMethod.POST)
    @ResponseBody
    public Object withdraw(HttpServletRequest request, Withdraw withdraw) {
        Integer userId = (Integer) request.getAttribute("userId");
        InstitutionAppUser ins = institutionAppUserService.getInstitutionById(userId);
        if (ins.getMoney() - withdraw.getMoney() < 0) {
            return NetDataAccessUtil.error().resultDesp("提现金额不可大于您的账号余额");
        }
        withdraw.setDealed(Constants.Withdraw_Undealed);
        withdraw.setFlag(Constants.INS_WITHDRAW);
        withdraw.setUserId(userId);
        withdraw.setTime(new Date());
        if (withdrawService.addWithdraw(withdraw, ins)) {
            return NetDataAccessUtil.success().resultDesp("提现申请成功，将于2-3个工作日内到账");
        }
        return NetDataAccessUtil.error().resultDesp("因网络或其他错误，提现失败，请稍后尝试");
    }

    /**
     * 获取机构信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getInstitutionInfo", method = RequestMethod.POST)
    @ResponseBody
    public Object getInstitutionInfo(HttpServletRequest request) {
        Integer userId = (Integer) request.getAttribute("userId");
        InstitutionView ins = institutionAppUserService.getInstitutionViewById(userId);
        if (ins != null) {
            ins.setPortrait("http://" + IPUtil.getIpAddr(request) + ":" + request.getLocalPort() + "/"
                    + Constants.IMAGE_PATH + ins.getPortrait());
            return NetDataAccessUtil.success().content(UserUtil.constructInsUserResp(ins, request.getParameter("token"))).resultDesp("获取机构信息成功");
        }
        return NetDataAccessUtil.error().resultDesp("获取机构信息失败");
    }

    /**
     * 机构修改用户名
     */
    @RequestMapping(value = "/account/update", method = RequestMethod.POST)
    @ResponseBody
    public NetDataAccessUtil updateAccount(Integer userId, String account) {
        if (StringUtils.isEmpty(account)) {
            return NetDataAccessUtil.error().resultDesp("用户名为空，请重新输入");
        }
        InstitutionAppUser ins = institutionAppUserService.getInstitutionById(userId);
        if (ins == null) {
            return NetDataAccessUtil.error().resultDesp("当前机构不存在");
        }
        if (ins.getAccount().equals(account)) {
            return NetDataAccessUtil.success().resultDesp("用户名修改成功");
        }
        // 正常修改逻辑：判断是否重名
        InstitutionView iv = institutionAppUserService.getInstitutionByAccount(account);
        if (iv != null) {
            return NetDataAccessUtil.error().resultDesp("用户名已被占用，请重新修改");
        }
        ins.setAccount(account);
        institutionAppUserService.updateInstitutionAppUser(ins);
        return NetDataAccessUtil.success().resultDesp("用户名修改成功");
    }

    @RequestMapping("/feeConf/add")
    @ResponseBody
    public NetDataAccessUtil addFeeConf(FeeConf feeConf) {
        if (feeConf.getInstitutionId() == null || feeConf.getUnitPrice() == null || feeConf.getBase() == null
                || feeConf.getCompl() == null || feeConf.getEmergency() == null || feeConf.getSpecial() == null) {
            return NetDataAccessUtil.error().resultDesp("必填参数存在空值");
        }
        InstitutionAppUser institutionAppUser = institutionAppUserService.getInstitutionById(feeConf.getInstitutionId());
        if (institutionAppUser == null){
            return NetDataAccessUtil.error().resultDesp("该机构不存在");
        }
        Integer id = feeConfService.insert(feeConf);
        feeConf.setId(id);
        return NetDataAccessUtil.success().content(feeConf).resultDesp("费用配置成功");
    }

}
